package Jdbc;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;

public class Utils {
    //封装连接对象
    public static Connection get_conn() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        return DriverManager.getConnection("jdbc:mysql://localhost:3306/books?useSSL=false","root","mysql");
    }
    public static void close(Connection conn)  {

        try {
            if(conn!=null){
            conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close(Statement statement){
        try {
            if(statement!=null){
            statement.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close(ResultSet resultSet){
        try {
            if(resultSet!=null){
            resultSet.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close(ResultSet resultSet,Statement statement,Connection conn){
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static Map<String,Object> get_one(String sql) throws SQLException, ClassNotFoundException {
        Map<String,Object> map=null;
        Connection conn=get_conn();
        PreparedStatement ps=conn.prepareStatement(sql);
        ResultSet re= ps.executeQuery();
        if(re.next()){
            map=new HashMap<>();
            ResultSetMetaData MetaData=re.getMetaData();
            System.out.println("我是MetaData"+MetaData);
            for(int i=1;i<MetaData.getColumnCount();i++){
                String str=MetaData.getColumnLabel(i);
                System.out.println("str--------"+str);
                Object value=re.getObject(i);
                System.out.println("VALUE----------"+value);
                map.put(str,value);

            }
        }
        close(conn);
        return map;
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        String sql="select id,title from t_book";
        Map<String,Object> map=get_one(sql);
        System.out.println(map.get("id"));
        System.out.println(map.get("title"));
    }
}
